package com.lin.fragments;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import com.sidingbar2.view.MySideBar;
import com.sidingbar2.view.PinyinUtils;
import com.t9search.util.PinyinUtil;
import com.lin.activity.AddFriendActivity;
import com.lin.activity.LauncherActivity;
import com.lin.activity.PersonalDetailCardActivity;
import com.lin.bean.CallHistoryBean;
import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Net;
import com.lin.utils.Parameters;
import com.lin.utils.Session;
import com.lin.utils.Utils;
import com.lin.views.CustomPopupWindow;
import com.lin.views.ListViewForRecentCall;
import com.lin.views.ListViewForRecentCall.OnItemListViewEventListener;
import com.lin.views.ListViewForRecentCallOfOutil;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.activity.ChatActivity;
import com.yunfeng.supercall.activity.FriendsDetailActivity;
import com.yunfeng.supercall.activity.MainActivity;
import com.yunfeng.supercall.activity.NotAFriendsActivity;
import com.yunfeng.supercall.activity.OutCallActivity;
import com.yunfeng.supercall.activity.MainActivity.DialPadSwitch;
import com.yunfeng.supercall.adapter.ContactsDialPadAdapter;
import com.yunfeng.supercall.bean.ChatMessageBean;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.ContactsBaseBean;
import com.yunfeng.supercall.bean.PhoneContactsBean;
import com.yunfeng.supercall.bean.RecentCallsBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.contactsutils.ContactsHelper;
import com.yunfeng.supercall.httputils.HttpClient;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;
import com.yunfeng.supercall.service.HandlePhoneDataIntentService;
import com.yunfeng.supercall.service.HandleRecentCallDataService;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.LayoutParams;

import com.lin.utils.Session.ResultReceiver;
import com.ly.quickdev.library.adapter.ListBaseAdapter.ViewHolder;
import com.ly.quickdev.library.utils.JsonUtils;


public class RecentCallFragment extends Fragment implements Constants,
OnItemListViewEventListener, OnItemLongClickListener, OnClickListener,
TextWatcher, OnTouchListener, DialPadSwitch, OnLongClickListener,
OnItemClickListener {

	public static List<SuperFriendsBean> superFriends;
	/** 用于实现T9搜索 */
	public static ContactsHelper mContactsHelper;


	private View mView;
	private ListViewForRecentCall mListview;
	private Session mSession;
	private boolean isInsertExecuted = false;
	private boolean isInsertDatabaseRunning = false;
	private boolean isSearchableInstant = true;
	private GridView mGridView;
	private View mHeaderView;
	/** 显示最近通话和搜索结果的adapter */
	private ContactsDialPadAdapter mAdapter;
	private ListViewForRecentCallOfOutil mListview2;
	private AudioManager mAudioManager;
	private SoundPool spool;
	public static final Map<String, Boolean> IS_SUPER = new HashMap<String, Boolean>();
	private ArrayList<RecentCallsBean> dataRecentCallsBean;
	/** 最近通话 */
	private EditText mTextViewDial;
	private Map<Integer, Integer> map = new HashMap<Integer, Integer>();
	private Activity mContext;
	//最开始字符 0显示这个
	private ArrayList<RecentCallsBean> mListRecentCalls;

	//最开始字符 0显示这个
	ArrayList<RecentCallsBean> mListRecentCallsInitiail = new ArrayList<RecentCallsBean>();

	//字符大于一通过这个搜索
	private List<SuperFriendsBean> mListSuperFriendsBean;
	private UpdateBroadcastReceiver mUpdateBroadcastReceiver;
	private UpdateBroadcastReceiver2  mUpdateBroadcastReceiver2;
	private List<SuperFriendsBean> mTempListSuperFriendsBean;
	private int mFriendsCount = 0;
	private SuperFriendsBean mSuperFriends;
	private ArrayList<PhoneContactsBean> mPhoneContacts;;
	private CustomPopupWindow pw;
	private SwipeRefreshLayout mSwipeRefreshLayout;
	private HorizontalScrollView mScrollView;
	public ProgressDialog mProgressDialog;
	private Button mButtonDial;
	private View mLinearLayoutGridView;
	private UserBean mUser;
	private RecentCallBroadcast mRecentCallBroadcast;
	private Thread mThread;

	private ImageView mImageViewSearch;
	private ImageView mImageViewMore;
	private ImageView mImageViewDelete;
	private ImageView mImageViewToChat;
	private ImageView mImageViewDeleteDial;

	private TextView mTextViewTitle;
	private TextView mTextViewArea;

	private LinearLayout mLinearLayout;


	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// mView = inflater.inflate(R.layout.fragment_dial_pad2, null);
		Log.i("TAG", "onCreateView");
		if (mView == null)
		{
			mView = inflater.inflate(R.layout.fragment_dial_pad2, null);
		}
		// 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) mView.getParent();
		if (parent != null)
		{
			parent.removeView(mView);
		}
		mUser = BaseActivity.getUser(getActivity());
		if (mListSuperFriendsBean == null) {
			mListSuperFriendsBean = new ArrayList<SuperFriendsBean>();
		}
		mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipe);
		mSwipeRefreshLayout.setEnabled(false);
		mSwipeRefreshLayout.setColorSchemeResources(R.color.base_orange);
		mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				mSwipeRefreshLayout.setRefreshing(true);
				load();
				readContacts();
			}
		});
		mGridView = (GridView) mView.findViewById(R.id.gridview);
		mScrollView = (HorizontalScrollView) mView.findViewById(R.id.scrollview);
		mGridView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return MotionEvent.ACTION_MOVE == event.getAction() ? true
						: false;
			}
		});

		mHeaderView = mView.findViewById(R.id.header);
		mTextViewDial = (EditText) mView.findViewById(R.id.textview_dial);
		mTextViewDial.setInputType(InputType.TYPE_NULL);
		mListview = (ListViewForRecentCall) mView.findViewById(R.id.listview);
		mListview2 = (ListViewForRecentCallOfOutil) mView.findViewById(R.id.listview2);
		mListview2.setOnItemClickListener(this);
		mListview2.setDataList(new ArrayList<RecentCallsBean>());
		mListview2.setVisibility(View.GONE);
		mButtonDial = (Button) mView.findViewById(R.id.btn_dial);
		mLinearLayoutGridView = mView.findViewById(R.id.grid_area);
		mContext = getActivity();
		mListRecentCalls = new ArrayList<RecentCallsBean>();
		mContactsHelper = ContactsHelper.getInstance(mContext);
		mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
		mGridView.setAdapter(new GridAdapter());
		loadSound();
		mSession = Session.getSession();
		mSession.init(getActivity(), true);
		load();
		//		getFriendsListIO();
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//				mScrollView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
				if (position < 12 && position != 9) {
					play(position);
				}
				if (position < 9) {
					mTextViewDial.append((position + 1) + "");
				}
				if (position == 10) {
					mTextViewDial.append("0");
				}
				mScrollView.scrollBy(20, 0);
				//				scrollToBottom(mScrollView , mTextViewDial);
				/*				mScrollView.postDelayed(new Runnable() {

					public void run() {
						mScrollView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
					}
				}, 1000L);*/
			}
		});
		/*	mListview.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				SuperFriendsBean mFriends = (SuperFriendsBean) mAdapter
						.getItem(position);
				deleteRecentCall(
						mListRecentCalls.get(position),
						position);
				Toast.makeText(mContext, "删除成功", Toast.LENGTH_LONG).show();
				return true;
			}
		});*/
		readContacts();
		/*mImageViewDelete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mTextViewDial.setText("");
			}
		});*/
		//============================================================================
		mImageViewSearch = (ImageView) mView.findViewById(R.id.imageview_search);
		mImageViewMore = (ImageView) mView.findViewById(R.id.imageview_more);
		mImageViewDelete = (ImageView) mView.findViewById(R.id.imageview_delete);
		mLinearLayout = (LinearLayout) mView.findViewById(R.id.linearLayout_bg);

		mTextViewTitle = (TextView) mView.findViewById(R.id.textview_title);
		mTextViewArea = (TextView) mView.findViewById(R.id.textview_area);

		mImageViewSearch.setOnClickListener(this);
		mImageViewMore.setOnClickListener(this);
		mImageViewDelete.setOnClickListener(this);
		mLinearLayout.setOnClickListener(this);

		mImageViewToChat = (ImageView) mView.findViewById(R.id.to_chat);
		mImageViewDeleteDial = (ImageView) mView.findViewById(R.id.delete);
		mImageViewToChat.setOnClickListener(this);
		mImageViewDeleteDial.setOnClickListener(this);
		mImageViewDeleteDial.setOnLongClickListener(this);	

		//============================================================================

		mListview.setOnTouchListener(this);
		mListview2.setOnTouchListener(this);
		mButtonDial.setOnClickListener(this);
		mListview.setOnItemListViewEventListener(this);
		//		mListview.setOnItemLongClickListener(this);
		mTextViewDial.addTextChangedListener(this);
		pw = new CustomPopupWindow(getActivity());
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_UPDATE_CALL);
		mUpdateBroadcastReceiver = new UpdateBroadcastReceiver();
		getActivity().registerReceiver(mUpdateBroadcastReceiver, filter);
		IntentFilter filter2 = new IntentFilter();
		filter2.addAction(ACTION_UPDATE_PHONE);
		mUpdateBroadcastReceiver2 = new UpdateBroadcastReceiver2();
		getActivity().registerReceiver(mUpdateBroadcastReceiver2, filter2);
		IntentFilter filter3 = new IntentFilter();
		filter3.addAction(ACTION_UPDATE_BROADCAST);
		mRecentCallBroadcast = new RecentCallBroadcast();
		getActivity().registerReceiver(mRecentCallBroadcast, filter3);
		return mView;
	}

	public static void scrollToBottom(final View scroll, final View inner) {
		Handler mHandler = new Handler();
		mHandler.post(new Runnable() {
			public void run() {
				if (scroll == null || inner == null) {
					return;
				}
				int offset = scroll.getWidth() - inner.getMeasuredWidth();
				if (offset < 0) {
					offset = 0;
				}
				scroll.scrollTo(0, offset);
			}
		});
	}

	private void load() {
		mSession.getCallHistory(getActivity(), 0, new ResultReceiver<ArrayList<RecentCallsBean>>(){
			boolean hasId(ArrayList<RecentCallsBean> data, RecentCallsBean bean) {
				mSwipeRefreshLayout.setRefreshing(false);
				for(Iterator<RecentCallsBean> iterator=data.iterator(); iterator.hasNext();) {
					RecentCallsBean bean2 = iterator.next();
					if(bean2.getUserid() == bean.getUserid()) {
						return true;
					}
				}
				return false;
			}

			@Override
			public void onResult(boolean last, ArrayList<RecentCallsBean> data) {
				// TODO Auto-generated method stub
				if(data != null) {
					dataRecentCallsBean = data;
					isInsertDatabaseRunning = true;
					if(HandlePhoneDataIntentService.isHandlePhoneDataIntentServiceRunning == false && isInsertExecuted == false) {
						DatabaseHelperForChattingMap dbHelper3 = new DatabaseHelperForChattingMap(getActivity(), "db", 2);
						if(dbHelper3 != null) {
							dbHelper3.insertSuperFrined2(dataRecentCallsBean);
						}
						isInsertExecuted = true;
						dbHelper3.close();
					}
					isInsertDatabaseRunning = false;
					ArrayList<RecentCallsBean> mListRecentCallsBean = new ArrayList<RecentCallsBean>(); 
					for(Iterator<RecentCallsBean> iterator=data.iterator(); iterator.hasNext();) {
						RecentCallsBean bean = iterator.next();
						Log.i("TAG", bean.getCalltime() + " " + bean.getNick_name() );
						if(!hasId(mListRecentCallsBean, bean)) {
							mListRecentCallsBean.add(bean);
						}
					}
					Collections.sort(mListRecentCallsBean, new Comparator<RecentCallsBean>() {
						@Override
						public int compare(RecentCallsBean lhs, RecentCallsBean rhs) {
							//						SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy/MM/dd HH:mm:ss " );
							//						String str = sdf.format(new Date());
							//						return -1;
							return (int) CompareDate(rhs.getCalltime(), lhs.getCalltime());
						}
					});
					if(data != null) {
						mListview.setDataList(mListRecentCallsBean);
						mListRecentCallsInitiail = new ArrayList<RecentCallsBean>(mListRecentCallsBean);
						mListRecentCalls = mListRecentCallsBean;
					}
				} else {
					DatabaseHelperForChattingMap dbHelper3 = new DatabaseHelperForChattingMap(getActivity(), "db", 2);
					ArrayList<RecentCallsBean> mListRecentCallsBean = null;
					if(dbHelper3 != null) {
						mListRecentCallsBean = dbHelper3.getRecentCallsBeanList();
					}
					dbHelper3.close();
					if(mListRecentCallsBean != null) {
						mListview.setDataList(mListRecentCallsBean);
						mListRecentCalls = mListRecentCallsBean;
					}
				}
			}
		});
	}

	public static long CompareDate(String date, String date1) {
		Log.i("tag", date);
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		try {
			Date d1 = df.parse(date);
			Date d2 = df.parse(date1);
			long diff = d1.getTime() - d2.getTime();
			return diff;
		}
		catch (Exception e) {
		}
		return 1;
	} 

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if(mUpdateBroadcastReceiver != null) {
			getActivity().unregisterReceiver(mUpdateBroadcastReceiver);
			mUpdateBroadcastReceiver = null;
		}
		if(mUpdateBroadcastReceiver2 != null) {
			getActivity().unregisterReceiver(mUpdateBroadcastReceiver2);
			mUpdateBroadcastReceiver2 = null;
		}
		if(mRecentCallBroadcast != null) {
			getActivity().unregisterReceiver(mRecentCallBroadcast);
			mRecentCallBroadcast = null;
		}
	}


	/*class ConnectionListener extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_CONNECTION_SUCCESS.equals(action)) {
				onConnectSuccess();
			}
			if (ACTION_CONNECTION_FAILED.equals(action)) {
				mHeaderView.setVisibility(View.VISIBLE);
			}
		}

	}

	private void onConnectSuccess() {
		mHeaderView.setVisibility(View.GONE);
	}*/

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * 拨号键盘
	 * 
	 * @author 洋
	 * 
	 */
	class GridAdapter extends BaseAdapter {
		private int mHeight;

		public GridAdapter() {
		}

		@Override
		public int getCount() {
			return 12;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(
						R.layout.grid_item_dial_pad, null);
			}
			int one = getResources()
					.getDimensionPixelOffset(R.dimen.grid_space);
			mHeight = (mGridView.getHeight() - ((getCount() / 3) - 1) * one)
					/ (getCount() / 3);
			LayoutParams layoutParams = new LayoutParams(
					LayoutParams.MATCH_PARENT, mHeight);

			convertView.setLayoutParams(layoutParams);
			TextView tv = ViewHolder.get(convertView, R.id.nums);
			TextView chars = ViewHolder.get(convertView, R.id.chars);
			convertView.setSoundEffectsEnabled(false);
			String str = BaseActivity.CHARS.get(position);
			if (!TextUtils.isEmpty(str)) {
				chars.setVisibility(View.VISIBLE);
				chars.setText(str);
			} else {
				chars.setVisibility(View.GONE);
			}
			if (position < 9) {
				tv.setText((position + 1) + "");
			} else {
				switch (position) {
				case 9:
					tv.setText("*");
					break;
				case 10:
					tv.setText("0");
					break;
				case 11:
					tv.setText("#");
					break;
				}
			}
			return convertView;
		}
	}

	@Override
	public void onItemAvatarLisener(RecentCallsBean maListInfo, int x, int y) {
		// TODO Auto-generated method stub
		//		Toast.makeText(getActivity(), "1" + maListInfo.getPhone(), Toast.LENGTH_LONG).show();
		startActivity(new Intent(getActivity(), PersonalDetailCardActivity.class)
		.putExtra("data", maListInfo));
	}

	@Override
	public void onItemClickListener(RecentCallsBean superFriends, int x, int y) {
		// mTextViewDial.setText(superFriends.getPhone());

		if (superFriends instanceof RecentCallsBean) {
			SuperFriendsManager friendsManager = (SuperFriendsManager) ManagerFactory
					.createManager(SuperFriendsBean.class);
			mSuperFriends = friendsManager
					.findSuperFriendsByPhone(superFriends.getPhone());
			if (mSuperFriends == null) {
				searchFriends(superFriends.getPhone());
			} else if (!Net.IsNetworkAvailble(mContext)) {
				Utils.dial(superFriends.getPhone(), mContext);
			} else {
				startActivity(new Intent(mContext, 
						OutCallActivity.class).putExtra(KEY_DATA,
								mSuperFriends));
				//				startActivity(new Intent(mContext, VideoConverseActivity.class));
			}
			return;
		}
		mSuperFriends = superFriends;
		if (superFriends.isContactsFromPhone()) {
			if (TextUtils.isEmpty(superFriends.getPhoto())) {
				// startActivity(new Intent(mContext,
				// NotAFriendsActivity.class).putExtra(KEY_DATA,
				// superFriends));
				mSession.searchUser(getActivity(), superFriends.getPhone(), new ResultReceiver<SuperFriendsBean>() {
					@Override
					public void onResult(boolean last, SuperFriendsBean mSuperFriends) {
						// TODO Auto-generated method stub
						if(mSuperFriends == null) return;
						try {
							if (mSuperFriends != null) {
								startActivity(new Intent(
										mContext,
										FriendsDetailActivity.class)
								.putExtra(KEY_DATA,
										mSuperFriends));
							} else {
								startActivity(new Intent(
										mContext,
										NotAFriendsActivity.class)
								.putExtra(KEY_DATA,
										mSuperFriends));
							}
						} catch (Exception e) {
							startActivity(new Intent(
									mContext,
									NotAFriendsActivity.class)
							.putExtra(KEY_DATA,
									mSuperFriends));
						}
					}

				});
			} else {
				startActivity(new Intent(mContext,
						FriendsDetailActivity.class).putExtra(KEY_DATA,
								superFriends));
			}
		} else {
			startActivity(new Intent(mContext,
					OutCallActivity.class).putExtra(KEY_DATA,
							mSuperFriends));
		}
		// if (!TextUtils.isEmpty(superFriends.getVo_id())) {
		// startActivity(new Intent(mContext, ChatActivity.class)
		// .putExtra(KEY_DATA, superFriends));
		// }
	}

	@Override
	public void onItemUserDetailListener(RecentCallsBean maListInfo, int x,
			int y) {
		// TODO Auto-generated method stub
		startActivity(new Intent(getActivity(), PersonalDetailCardActivity.class)
		.putExtra(KEY_DATA, maListInfo));
		//		Toast.makeText(getActivity(), "3" + maListInfo.getPhone(), Toast.LENGTH_LONG).show();
	}

	/**
	 * 加载拨号音
	 */
	private void loadSound() {
		if (spool != null) {
			return;
		}
		spool = new SoundPool(11, AudioManager.STREAM_SYSTEM, 5);
		map.put(10, spool.load(getActivity(), R.raw.dtmf0, 0));
		map.put(0, spool.load(getActivity(), R.raw.dtmf1, 0));
		map.put(1, spool.load(getActivity(), R.raw.dtmf2, 0));
		map.put(2, spool.load(getActivity(), R.raw.dtmf3, 0));
		map.put(3, spool.load(getActivity(), R.raw.dtmf4, 0));
		map.put(4, spool.load(getActivity(), R.raw.dtmf5, 0));
		map.put(5, spool.load(getActivity(), R.raw.dtmf6, 0));
		map.put(6, spool.load(getActivity(), R.raw.dtmf7, 0));
		map.put(7, spool.load(getActivity(), R.raw.dtmf8, 0));
		map.put(8, spool.load(getActivity(), R.raw.dtmf9, 0));
		map.put(11, spool.load(getActivity(), R.raw.dtmf11, 0));
		map.put(9, spool.load(getActivity(), R.raw.dtmf12, 0));
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		return false;
	}

	private void deleteRecentCall(RecentCallsBean calls, final int position) {
		JSONObject json = BaseActivity.getBaseParams(mContext);
		try {
			json.put("i_callid", calls.getCallid());
			json.put("i_user1", calls.getUser1());
			json.put("i_user2", calls.getUser2());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		showProgressDialog(getResources().getString(R.string.deleting));

		HttpClient mHttpClient;
		mHttpClient = new HttpClient();
		mHttpClient.post(FUNCTION_DELETE_CALL_HISTORY, json,
				new MyAjaxCallBack() {
			@Override
			public void onReceiveError(String msg, String errorCode) {
				cancelProgressDialog();
			}

			@Override
			public void onReceiveData(String data, String msg) {
				cancelProgressDialog();
				mListRecentCalls.remove(position);
				mListview.setDataList(mListRecentCalls);
				//				mAdapter.notifyDataSetChanged();
			}
		});
	}

	public void showProgressDialog(String msg) {
		if (mProgressDialog == null) {
			mProgressDialog = new ProgressDialog(getActivity());
			mProgressDialog.setCancelable(false);
		}
		if (TextUtils.isEmpty(msg)) {
			msg = "正在加载数据...";
		}
		mProgressDialog.setMessage(msg);
		mProgressDialog.show();
	}

	public void cancelProgressDialog() {
		if (mProgressDialog != null) {
			mProgressDialog.cancel();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.linearLayout_bg:
			break;
		case R.id.to_chat:
			Utils.createUser(getActivity());
			break;
		case R.id.imageview_search:
			startActivity(new Intent(getActivity(), AddFriendActivity.class));
			break;
		case R.id.imageview_more:
			pw.show();
			break;
		case R.id.imageview_delete:
			mTextViewDial.setText("");
			break;
		case R.id.btn_dial:
			if (mLinearLayoutGridView.getVisibility() == View.GONE) {
				mLinearLayoutGridView.setVisibility(View.VISIBLE);
				return;
			}
			String phone = mTextViewDial.getText().toString();
			if (TextUtils.isEmpty(phone)) {
				return;
			}
			SuperFriendsManager manager = (SuperFriendsManager) ManagerFactory
					.createManager(SuperFriendsBean.class);
			SuperFriendsBean mFriends = manager.findSuperFriendsByPhone(phone);
			if (mFriends == null) {
				searchFriends(phone);
			} else {
				startActivity(new Intent(mContext, OutCallActivity.class)
				.putExtra(KEY_DATA, mFriends));
			}
			break;
		case R.id.delete:
			String text = mTextViewDial.getText().toString();
			if (!TextUtils.isEmpty(text)) {
				mTextViewDial.setText(text.substring(0, text.length() - 1));
				mTempListSuperFriendsBean = searchList(mTextViewDial.getText().toString(), mListSuperFriendsBean);
				Intent intent = new Intent(getActivity(), HandleRecentCallDataService.class);
				intent.putExtra("data", mTextViewDial.getText().toString());
				getActivity().startService(intent);
			}
			break;
		}

		/*if(mButtonDial == v) {
			pw.show();
			if (mLinearLayoutGridView.getVisibility() == View.GONE) {
				mLinearLayoutGridView.setVisibility(View.VISIBLE);
				return;
			}
			String phone = mTextViewDial.getText().toString();
			if (TextUtils.isEmpty(phone)) {
				return;
			}
			SuperFriendsManager manager = (SuperFriendsManager) ManagerFactory
					.createManager(SuperFriendsBean.class);
			SuperFriendsBean mFriends = manager.findSuperFriendsByPhone(phone);
			if (mFriends == null) {
				searchFriends(phone);
			} else {
				startActivity(new Intent(mContext, OutCallActivity.class)
				.putExtra(KEY_DATA, mFriends));
			}
		}else if (mTextViewDelete == v) { 
			String text = mTextViewDial.getText().toString();
			if (!TextUtils.isEmpty(text)) {
				mTextViewDial.setText(text.substring(0, text.length() - 1));
				mTempListSuperFriendsBean = searchList(mTextViewDial.getText().toString(), mListSuperFriendsBean);
			}
		}*/

		/*if (mTextViewToChat == v) {
			Utils.createUser(getActivity());
			if (mSuperFriends != null && !mSuperFriends.isContactsFromPhone()) {
				startActivity(new Intent(mContext, ChatActivity.class)
				.putExtra(KEY_DATA, mSuperFriends));
			}
		} else if(mFrameLayoutMore == v) {
			pw.show();		
		} else if(mImageViewMore == v) {
			if(pw.isShowing()){
				pw.dismiss();
			}else{
				View parent = getActivity().getWindow().getDecorView();//��ô��壬��popupwindow�ĸ��ؼ�
				DisplayMetrics metric = new DisplayMetrics();
				getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
				int width = metric.widthPixels;     // 屏幕宽度（像素）
				pw.showAtLocation(parent, Gravity.NO_GRAVITY, width, (int) getResources().getDimension(R.dimen.top_bar) + 60);//��ʾ����Ļ�м�
			}
		} else if(v == mFrameLayoutSearch) {
			startActivity(new Intent(getActivity(), AddFriendActivity.class));
		} else if(v.getId() == R.id.btn_dial) {
			if (mLinearLayoutGridView.getVisibility() == View.GONE) {
				mLinearLayoutGridView.setVisibility(View.VISIBLE);
				return;
			}
			String phone = mTextViewDial.getText().toString();
			if (TextUtils.isEmpty(phone)) {
				return;
			}
			SuperFriendsManager manager = (SuperFriendsManager) ManagerFactory
					.createManager(SuperFriendsBean.class);
			SuperFriendsBean mFriends = manager.findSuperFriendsByPhone(phone);
			if (mFriends == null) {
				searchFriends(phone);
			} else {
				startActivity(new Intent(mContext, OutCallActivity.class)
				.putExtra(KEY_DATA, mFriends));
			}
		}else if(v.getId() == R.id.delete) {
			String text = mTextViewDial.getText().toString();
			if (!TextUtils.isEmpty(text)) {
				mTextViewDial.setText(text.substring(0, text.length() - 1));
				mTempListSuperFriendsBean = searchList(mTextViewDial.getText().toString(), mListSuperFriendsBean);
				Intent intent = new Intent(getActivity(), HandleRecentCallDataService.class);
				intent.putExtra("data", mTextViewDial.getText().toString());
				getActivity().startService(intent);
			}
		} else if(v.getId() == R.id.imageview_delete) {
			mTextViewDial.setText("");
		}*/
	}

	public class RunnableSearchList implements Runnable {
		String str;
		List<SuperFriendsBean> data;


		public RunnableSearchList(String str, List<SuperFriendsBean> data) {
			super();
			this.str = str;
			this.data = data;
		}


		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (str.isEmpty()) {
				return ;
			}

			superFriends = new ArrayList<SuperFriendsBean>();
			try {
				mContactsHelper.parseT9InputSearchContacts(str);
			} catch(Exception e) {

			}
			superFriends.addAll(mContactsHelper.getSearchContacts());
			mHandlerSearchList.sendEmptyMessage(0);
		}

		Handler mHandlerSearchList = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				mAdapter = new ContactsDialPadAdapter(mContext, superFriends);
				mAdapter.setReplaceText(mTextViewDial.getText().toString());
				mListview.setAdapter(mAdapter);
				if(superFriends.size() > 0) {
					mListview.setVisibility(View.VISIBLE);
					mListview2.setVisibility(View.GONE);
				} else {
					mListview.setVisibility(View.GONE);
					mListview2.setVisibility(View.VISIBLE);
				}
			}
		};
	}

	/*	Runnable mRunnableSearchList = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
	};*/

	/**
	 * 搜索联系人
	 * 
	 * @param str
	 * @param data
	 * @return
	 */
	private List<SuperFriendsBean> searchList(String str, List<SuperFriendsBean> data) {
		if (str.isEmpty()) {
			return mListSuperFriendsBean;
		}

		final List<SuperFriendsBean> SuperFriends = new ArrayList<SuperFriendsBean>();
		try {
			mContactsHelper.parseT9InputSearchContacts(str);
		} catch(Exception e) {

		}
		SuperFriends.addAll(mContactsHelper.getSearchContacts());
		mAdapter = new ContactsDialPadAdapter(mContext, SuperFriends);
		mAdapter.setReplaceText(mTextViewDial.getText().toString());
		mListview.setAdapter(mAdapter);
		if(SuperFriends.size() > 0) {
			mListview.setVisibility(View.VISIBLE);
			mListview2.setVisibility(View.GONE);
		} else {
			mListview.setVisibility(View.GONE);
			mListview2.setVisibility(View.VISIBLE);
		}
		return data;
	}

	private void searchFriends(final String phone) {

		mSession.searchUser(mContext, phone, new ResultReceiver<SuperFriendsBean>() {

			@Override
			public void onResult(boolean last, SuperFriendsBean mSuperFriends) {
				// TODO Auto-generated method stub
				try {
					if (mSuperFriends != null
							&& mSuperFriends.getVo_id() != null) {
						startActivity(new Intent(mContext,
								OutCallActivity.class).putExtra(KEY_DATA,
										mSuperFriends));
					} else {
						Toast.makeText(mContext, RecentCallFragment.this.getResources().getString(R.string.super_number_not_found), Toast.LENGTH_LONG).show();
						Utils.dial(phone, getActivity());
					}
				} catch(Exception e) {
					Toast.makeText(mContext, RecentCallFragment.this.getResources().getString(R.string.super_number_not_found), Toast.LENGTH_LONG).show();
				}
			}

		});

	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		//		if(isSearchable == false) return;

		if (s == null || s.length() == 0) {
			try {
				mScrollView.setVisibility(View.GONE);
				//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				mListview.setDataList(new ArrayList<RecentCallsBean>(mListRecentCallsInitiail));
				mTextViewTitle.setVisibility(View.VISIBLE);
				mImageViewSearch.setVisibility(View.VISIBLE);
				mImageViewMore.setVisibility(View.VISIBLE);
				mImageViewDelete.setVisibility(View.GONE);
				mListview.setVisibility(View.VISIBLE);
				mListview2.setVisibility(View.GONE);
			} catch(NullPointerException e) {

			}
		} else {
			try {

				mTextViewTitle.setVisibility(View.GONE);
				mScrollView.setVisibility(View.VISIBLE);
				//mTextViewArea.setVisibility(View.VISIBLE);
				mImageViewSearch.setVisibility(View.GONE);
				mImageViewMore.setVisibility(View.GONE);
				mImageViewDelete.setVisibility(View.VISIBLE);
				mTextViewDial.setVisibility(View.VISIBLE);
				if (s.length() > 1) {
					Intent intent = new Intent(getActivity(), HandleRecentCallDataService.class);
					intent.putExtra("data", mTextViewDial.getText().toString());
					getActivity().startService(intent);
				}
			} catch(NullPointerException e) {

			}
		}
	}

	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Intent intent = new Intent(getActivity(), HandleRecentCallDataService.class);
			intent.putExtra("data", mTextViewDial.getText().toString());
			getActivity().startService(intent);
			isSearchableInstant = true;
		}

	};


	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 300:
				mGridView.post(new Runnable() {

					@Override
					public void run() {
						if(mPhoneContacts != null)
							queryFriends(mPhoneContacts);
					}
				});

				break;
			}
		};
	};

	/**
	 * 在服务器上对比通讯录和好友
	 */
	private void queryFriends(List<PhoneContactsBean> contacts) {
		IS_SUPER.clear();
		if (contacts == null || contacts.isEmpty()) {
			return;
		}
		String phones = "";
		for (PhoneContactsBean phoneContacts : contacts) {
			phones += phoneContacts.getPhone() + ";";
		}
		if (TextUtils.isEmpty(phones)) {
			return;
		}
		phones = phones.substring(0, phones.length() - 1);

		mSession.checkLocalAddressBook(getActivity(), phones, new ResultReceiver<ArrayList<SuperFriendsBean>>() {

			@Override
			public void onResult(boolean last, ArrayList<SuperFriendsBean> mFriends) {
				// TODO Auto-generated method stub
				if(mFriends == null) return;
				if (mFriends != null && !mFriends.isEmpty()) {
					for (SuperFriendsBean s : mFriends) {
						// s.setContactsFromPhone(true);
						IS_SUPER.put(s.getPhone(), true);
					}
					// mFriends.removeAll(mRealFriends);
					// mList.addAll(mFriendsCount, mFriends);
					// mAdapter.notifyDataSetChanged();

				}
			}

		});
	}


	private static ArrayList<PhoneContactsBean>  getPeopleInPhone2(Context mContext) {
		ArrayList<PhoneContactsBean> list = new ArrayList<PhoneContactsBean>();

		Cursor cursor = mContext.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null); // 获取手机联系人
		int cpt = 0;
		while (cursor.moveToNext() ) {

			int indexPeopleName = cursor.getColumnIndex(Phone.DISPLAY_NAME); // people
			// name
			int indexPhoneNum = cursor.getColumnIndex(Phone.NUMBER); // phone
			// number

			String strPeopleName = cursor.getString(indexPeopleName);
			String strPhoneNum = cursor.getString(indexPhoneNum);
			PhoneContactsBean map = new PhoneContactsBean();

			map.setNick_name(strPeopleName);
			PinyinUtil.chineseStringToPinyinUnit(map.getNick_name(),
					map.getNamePinyinUnits());
			map.setPhone(strPhoneNum);
			map.setContactsFromPhone(true);
			list.add(map);
		}
		if (!cursor.isClosed()) {
			cursor.close();
			cursor = null;
		}
		cpt ++ ;
		Collections.sort(list);
		//		mPhoneContacts = list;
		return list;
	}

	private void readContacts() {
		if (!mListSuperFriendsBean.isEmpty()) {
			mHandler.sendEmptyMessage(300);
			return;
		}
		Thread thread = new Thread(runnalbe);
		thread.setPriority(Thread.MIN_PRIORITY);
		thread.start();
	}

	Runnable runnalbe = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				if(Parameters.mArrayListPhoneContactsBean != null) {
					mListSuperFriendsBean.addAll(Parameters.mArrayListPhoneContactsBean);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			getFriendsListIO();
		};
	};


	private synchronized void getFriendsListIO() {
		try {
			mSession.getFriendList(getActivity(), mUser.getUserid(), 0, new ResultReceiver<ArrayList<SuperFriendsBean>>(){
				@Override
				public void onResult(boolean last, ArrayList<SuperFriendsBean> data) {
					// TODO Auto-generated method stub
					if(data == null) return;
					ArrayList<SuperFriendsBean> mRealFriendsList;
					mRealFriendsList = data;
					if(data != null) {
						Collections.sort(mRealFriendsList);
						mFriendsCount = mRealFriendsList.size();

						// 查找已经是超号用户的联系人
						if (mPhoneContacts != null) {
							List<SuperFriendsBean> friends = new ArrayList<SuperFriendsBean>();
							for (SuperFriendsBean phone : mPhoneContacts) {
								for (SuperFriendsBean f : mRealFriendsList) {
									if (f.getPhone().equals(phone.getPhone())) {
										((PhoneContactsBean) phone).setSuperNum(true);
										friends.add(phone);
										// continue;
									}
								}
							}
							mListSuperFriendsBean.removeAll(friends);
							// mPhoneContacts.removeAll(friends);
							Collections.sort(mPhoneContacts);
						}
						ManagerFactory.createManager(PhoneContactsBean.class).saveList(
								mPhoneContacts);
						mListSuperFriendsBean.addAll(0, mRealFriendsList);
						ManagerFactory.createManager(SuperFriendsBean.class).saveList(
								mRealFriendsList);
						mContactsHelper.setBaseContacts(mListSuperFriendsBean);
						mHandler.sendEmptyMessage(300);
					}
				}

			});
		} catch(NullPointerException e) {

		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (event.getActionMasked()) {
		case MotionEvent.ACTION_MOVE:
			if (mLinearLayoutGridView.getVisibility() == View.VISIBLE) {
				mLinearLayoutGridView.startAnimation(AnimationUtils.loadAnimation(
						mContext, R.anim.push_out__up_to_down));
				/*MainActivity mMainActivity = (MainActivity) getActivity();
				mMainActivity.mLinearLayoutDial.setVisibility(View.GONE);
				 */
				mLinearLayoutGridView.setVisibility(View.GONE);
			}
			break;
		}
		return false;
	}

	/**
	 * 播放拨号音
	 * 
	 * @param id
	 */
	private void play(int id) {
		int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		//		int current = mAudioManager.getStreamVolume(AudioManager.STREAM_RING );
		int current = 0;
		float value = (float) 0.7 / max * current;
		spool.setVolume(spool.play(map.get(id), value, value, 0, 0, 1f), value,
				value);
	}

	@Override
	public void toggle() {
		// TODO Auto-generated method stub
		View v = mLinearLayoutGridView;
		if (v == null) {
			return;
		}
		if (v.getVisibility() == View.VISIBLE) {
			v.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_out__up_to_down));
			v.setVisibility(View.GONE);
			/*MainActivity mMainActivity = (MainActivity) getActivity();
			mMainActivity.mLinearLayoutDial.setVisibility(View.GONE);*/
		} else {
			/*MainActivity mMainActivity = (MainActivity) getActivity();
			mMainActivity.mLinearLayoutDial.setVisibility(View.GONE);*/
			v.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_in_down_to_up));
			v.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void toggleUp() {
		// TODO Auto-generated method stub
		/*MainActivity mMainActivity = (MainActivity) getActivity();
		mMainActivity.mLinearLayoutDial.setVisibility(View.GONE);*/
		View v = mLinearLayoutGridView;
		if (v == null) {
			return;
		}
		v.startAnimation(AnimationUtils.loadAnimation(mContext,
				R.anim.push_in_down_to_up));
		v.setVisibility(View.VISIBLE);
	}

	@Override
	public boolean onLongClick(View arg0) {
		// TODO Auto-generated method stub
		mTextViewDial.setText("");
		return false;
	}

	class UpdateBroadcastReceiver extends BroadcastReceiver {
		public UpdateBroadcastReceiver() {

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			load();
		}
	}

	class UpdateBroadcastReceiver2 extends BroadcastReceiver {
		public UpdateBroadcastReceiver2() {

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(Parameters.mArrayListPhoneContactsBean != null) {
				mListSuperFriendsBean.addAll(Parameters.mArrayListPhoneContactsBean);
				//				new Thread(mRunnableFilterDataInPhone).start();
			}

			if(Parameters.mArrayListPhoneContactsBean != null) {
				if(isInsertDatabaseRunning == false && isInsertExecuted == false) {
					DatabaseHelperForChattingMap dbHelper3 = new DatabaseHelperForChattingMap(getActivity(), "db", 2);
					if(dbHelper3 != null) {
						if(dataRecentCallsBean != null)
							dbHelper3.insertSuperFrined2(dataRecentCallsBean);
						dbHelper3.insertSuperFriendsUserInfoFromRecentCallBean(dataRecentCallsBean);
					}
					dbHelper3.close();
				}
			}
			isInsertDatabaseRunning = true;
			Log.i("tag4", "begin inserting");
			if(HandlePhoneDataIntentService.isHandlePhoneDataIntentServiceRunning == false) {
				DatabaseHelperForChattingMap dbHelper3 = new DatabaseHelperForChattingMap(getActivity(), "db", 2);
				if(dbHelper3 != null) {
					//									dbHelper3.insertSuperFrined2(dataRecentCallsBean);
					dbHelper3.insertRecentCallsBeanList(mListRecentCalls);
				}
				dbHelper3.close();
				isInsertExecuted = true;
			}
			isInsertDatabaseRunning = false;
		}
	}

	boolean isLoadedFirstTime = false;

	Runnable mRunnableFilterDataInPhone = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			ArrayList<CallHistoryBean> mData = getCallHistory2();
			if(isLoadedFirstTime != true) {
				for(Iterator<PhoneContactsBean> iterator2=Parameters.mArrayListPhoneContactsBean.iterator();iterator2.hasNext();)	{
					PhoneContactsBean mSuperFriendsBean = iterator2.next();
					for(Iterator<CallHistoryBean> iterator = mData.iterator(); iterator.hasNext();) {
						CallHistoryBean mBean = iterator.next();
						try {
							if(mBean.getNumber().equals(mSuperFriendsBean.getPhone())) {
								RecentCallsBean mBean2 = new RecentCallsBean();
								mBean2.setTypeIsDataInPhone(true);
								mBean2.setPhone(mSuperFriendsBean.getPhone());
								mBean2.setNick_name(mBean.getName());
								mBean2.setCalltime(mBean.getDate());
								mBean2.setType(mBean.getType());
								if(!isContainObjectRecentCallsBean(mListRecentCallsInitiail, mBean2)) {
									mListRecentCallsInitiail.add(mBean2);
								}
								break;

							}
						} catch(NullPointerException e) {

						}
					}
				}
				isLoadedFirstTime = true;
			}

			mHandlerFilterDataInPhone.sendEmptyMessage(0);
		}

	};

	Handler mHandlerFilterDataInPhone = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			mListview.setDataList(mListRecentCallsInitiail);

		}

	};

	Runnable mRunnableInserting = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub

		}
	};

	@Override
	public void onItemLongCListener(RecentCallsBean maListInfo, int x, int y) {
		// TODO Auto-generated method stub
		SuperFriendsBean mFriends = maListInfo;
		int position = mListRecentCalls.indexOf(mFriends);
		deleteRecentCall(
				mListRecentCalls.get(position),
				position);
		Toast.makeText(mContext, "删除成功", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub
		String number = mTextViewDial.getText().toString();
		if(position == 0) {
			Toast.makeText(getActivity(), "暂时不提供该功能尽请期待", Toast.LENGTH_LONG).show();
		} else if(position == 1) {
			//			Utils.createUser(getActivity());
			Utils.addContact(getActivity(), "", number, "", "") ;

		} else if(position == 2) {
			Utils.SendSMSTo(getActivity(), number);
		} 
	}

	public class RecentCallBroadcast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Log.i("tag123", "RecentCallBroadcast");
			try {
				mAdapter = new ContactsDialPadAdapter(mContext, superFriends);
				mAdapter.setReplaceText(mTextViewDial.getText().toString());
				mListview.setAdapter(mAdapter);
			} catch(Exception e) {
				e.printStackTrace();
			}
			if(superFriends.size() > 0) {
				mListview.setVisibility(View.VISIBLE);
				mListview2.setVisibility(View.GONE);
			} else {
				mListview.setVisibility(View.GONE);
				mListview2.setVisibility(View.VISIBLE);
			}
		}
	}

	ArrayList<CallHistoryBean> getCallHistory2 () {
		ArrayList<CallHistoryBean> mList = new ArrayList<CallHistoryBean>();
		Date date;
		ContentResolver cr = getActivity().getContentResolver();
		final Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI, new String[] {
				CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME,
				CallLog.Calls.TYPE, CallLog.Calls.DATE, CallLog.Calls.DURATION }, null, null,
				CallLog.Calls.DEFAULT_SORT_ORDER);
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			//			String number = cursor.getString(0);

			String number = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
			String name = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME));                 
			//通话时间,单位:s                                                                                      
			//			String duration = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.DURATION));
			long duration = cursor.getLong(cursor.getColumnIndexOrThrow(CallLog.Calls.DURATION));
			String callTime = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.DATE)); 
			SimpleDateFormat sfd = new SimpleDateFormat("MM-dd hh:mm:ss");
			date = new Date(Long.parseLong(callTime));
			String strDate = sfd.format(date);
			int type = cursor.getInt(2);
			CallHistoryBean mCallHistoryBean = new CallHistoryBean(strDate , number, name, duration + "", type);
			mList.add(mCallHistoryBean);
		}
		return mList;
	} 

	boolean isContainObjectRecentCallsBean(ArrayList<RecentCallsBean> mListRecentCalls, RecentCallsBean object) {
		if(object.getNick_name().trim().length() == 0) return true;
		for(Iterator<RecentCallsBean> iterator=mListRecentCalls.iterator();iterator.hasNext();) {
			RecentCallsBean mRecentCallsBean =  iterator.next();
			if(mRecentCallsBean.getNick_name().equalsIgnoreCase(object.getNick_name())) {
				return true;
			}
		}
		return false;
	}
}